<template>
  <div class="goodsAttr">
    <el-card>
      <template #header>
        <el-icon><SetUp /></el-icon>
        <span>商品属性</span>
      </template>
      <template #default>
        <el-form ref="formRef" :model="form" :rules="rules" size="large" label-width="150">
          <el-form-item label="属性分类" prop="attributeCategoryId" required>
            <el-select
              class="input-w"
              v-model="form.attributeCategoryId"
              filterable
              remote
              remote-show-suffix 
              clearable 
              placeholder="请输入属性分类名称查询"
              :remote-method="loadAttrTypes"
              :loading="loading"
              @change="loadGoodSpecs">
              <el-option v-for="item in attrTypes" :key="item.attributeCategoryId" :label="item.name" :value="item.attributeCategoryId"/>
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.attributeCategoryId" label="商品规格" prop="skuList" required>
            <div class="good_specs">
              <div class="specs-box">
                <div v-for="item in specs" :key="item.attributeId" class="specs_item">
                  <div class="name">{{ item.name }}</div>
                  <div 
                    class="specs_value" 
                    v-for="itemC in item.attributeValueList" 
                    :key="itemC.attributeValueId" 
                    :class="{'specs_active': chooseSpecs.includes(itemC.attributeValueId)}" 
                    @click="doChooseSpecs(item.attributeId, itemC.attributeValueId)">
                    {{ itemC.attributeValue }}
                  </div>
                </div>
              </div>
              <div>
                <el-button type="primary" plain @click="doRefreshSpecs">刷新规格</el-button>
                <el-button type="primary" plain @click="doSyncData('oriPrice')">同步出厂价</el-button>
                <el-button type="primary" plain @click="doSyncData('salePrice')">同步销售价</el-button>
                <el-button type="primary" plain @click="doSyncData('stocks')">同步库存</el-button>
                <el-button type="primary" plain @click="doSyncData('lowStock')">同步库存预警值</el-button>
                <el-button type="primary" plain @click="doSyncData('giftPoint')">同步赠送积分</el-button>
                <el-button type="primary" plain @click="doSyncData('agentPoint')">同步金送积分</el-button>
              </div>
              <el-table :data="form.skuList" :header-cell-style="{fontSize:'12px'}"  max-height="500" border size="small">
                <el-table-column v-for="item in tableHeader" :key="item.prop" :label="item.label" :prop="item.prop" :fixed="item.prop.indexOf('specs') !== -1" align="center">
                  <template #default="{row}">
                    <div v-if="item.prop === 'skuPic'" class="sku-pic-box">
                      <upload-img v-model="row.skuPic" width="40" height="40" iconSize="20" style="margin-top: -10px;"></upload-img>
                    </div>
                    <span v-else-if="/^\d+$/.test(item.prop)">{{ row[item.prop] }}</span>
                    <el-input v-else v-model="row[item.prop]" type="number" placeholder="请输入" size="small"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="60" fixed="right">
                  <template #default="{$index}">
                    <el-button type="danger" link @click="form.skuList.splice($index, 1)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
          <el-form-item v-if="form.attributeCategoryId" label="商品参数" prop="paramBindList" required>
            <div class="good_params">
              <div class="good_param_item" v-for="item in argumentList" :key="item.id">
                <span class="paramName">{{ item.name }}</span>
                <el-input v-model="item.attributeValues" :placeholder="'请输入'+item.name" clearable/>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div class="btns">
          <el-button size="large" @click="doClose">返回</el-button>
          <el-button type="primary" size="large" @click="doPrevStep">上一步</el-button>
          <el-button type="primary" size="large" @click="doNextStep">下一步</el-button>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup name="goodsAttr">
  import { getGoodsAttrTypeListApi, getGoodsAttrApi, getGoodsParamsApi, saveOrUpdateGoodsAttrInfoApi, getGoodsAttrInfoApi } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
  import { useStore } from 'vuex' 

  const store = useStore()

  const currentThis = getCurrentInstance().appContext.config.globalProperties
  const formRef = ref(null)
  const emits = defineEmits(['prevStep', 'nextStep', 'close'])
  defineExpose({init}) // 抛出组件方法供父组件使用

  const currentData = reactive({
    loading: false,
    attrTypes: [],
    chooseSpecs: [],
    specs: [],
    argumentList: [],
    tableHeader: [],
    form: {
      productId: '',
      attributeCategoryId: '',
      attributeBindList: [],
      skuList: [],
      paramBindList: []
    },
    rules: {
      attributeCategoryId: [{ required: true, message: '请选择属性分类', trigger: ['blur', 'change'] }],
      skuList: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(value.length === 0) {
              callback(new Error('请选择商品规格'))
            } else {
              callback()
            }
          } 
        }
      ],
      paramBindList: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            for (let i = 0; i < currentData.argumentList.length; i++) {
              let element = currentData.argumentList[i]
              if(!element.attributeValues) {
                callback(new Error(`请输入${element.name}`))
              }
            }
            callback()
          } 
        }
      ]
    }
  })
  let {loading, attrTypes, chooseSpecs, specs, argumentList, tableHeader, form, rules} = toRefs(currentData)

  // 初始化数据
  function init() {
    currentData.form.productId = store.state.productId
    if(currentData.form.productId) {
      getGoodsAttrInfoApi(currentData.form.productId).then(res => {
        if(res.code === '200') {
          currentData.form.attributeCategoryId = res.data.attributeCategoryId || ''
          currentData.form.skuList = res.data.sku.infoList
          currentData.argumentList = res.data.paramBindList
          if(currentData.form.attributeCategoryId) {
            loadGoodsAttr(currentData.form.attributeCategoryId)
            currentData.attrTypes = [{attributeCategoryId: res.data.attributeCategoryId, name: res.data.name}]
          }
          let timer = setTimeout(() => {
            let chooseSpecs = []
            let attributeBindList = []
            res.data.attributeBindList.forEach(item => {
              item.valueList.forEach(e => {
                chooseSpecs.push(e.attributeValueId)
                attributeBindList.push({attributeId: item.attributeId, attributeValueId: e.attributeValueId})
              })
            })
            currentData.chooseSpecs = chooseSpecs
            currentData.form.attributeBindList = attributeBindList
            clearTimeout(timer)
          }, 500)
        }
      })
    }
  }

  // 上一步
  function doPrevStep() {
    emits('prevStep')
  }

  // 下一步
  function doNextStep() {
    formRef.value.validate((valid) => {
      if(valid) {
        currentData.form.paramBindList = currentData.argumentList.map(item => {
          return {attributeId: item.attributeId, attributeValue: item.attributeValues}
        })
        saveOrUpdateGoodsAttrInfoApi(currentData.form).then(res => {
          if(res.code === '200') {
            emits('nextStep')
          } else {
            currentThis.$message.error(res.message)
          }
        })
      }
    })
  }

  // 关闭
  function doClose() {
    emits('close')
  } 

  // 商品规格中每条规格点击时候执行（选中，取消选中）
  function doChooseSpecs(attributeId, attributeValueId) {
    if(currentData.chooseSpecs.includes(attributeValueId)) { // 取消选中
      currentData.chooseSpecs.splice(currentData.chooseSpecs.indexOf(attributeValueId), 1)
      currentData.form.attributeBindList = currentData.form.attributeBindList.filter(item => {
        return item.attributeValueId !== attributeValueId
      })
    } else {
      currentData.chooseSpecs.push(attributeValueId) // 选中
      currentData.form.attributeBindList.push({attributeId: attributeId, attributeValueId: attributeValueId})
    }
  }

  // 点击刷新规格按钮执行
  function doRefreshSpecs() {
    if(!currentData.chooseSpecs.length) {
      currentThis.$message.error('请选择商品规格')
      return
    }
    // 获取被选中规格数据
    let specsObj = {}
    for (let i = 0; i < currentData.specs.length; i++) {
      const item = currentData.specs[i]
      specsObj[item.attributeId] = {
        specsName: item.name,
        list: []
      }
      item.attributeValueList.forEach(e => {
        if(currentData.chooseSpecs.includes(e.attributeValueId)) {
          specsObj[item.attributeId].list.push(e)
        }
      })
      if(!specsObj[item.attributeId].list.length) {
        currentThis.$message.error(`请选择${item.name}规格`)
        return
      }
    }
    createTableData(specsObj)
  }
  
  // 根据所选规格数据，计算出规格数据成表
  function createTableData(specsObj) {
    let skuItem = {
      skuPic: '',     // SKU图标
      skuName: '',    // SKU名称
      oriPrice: '',   // 出厂价
      salePrice: '',  // 销售价
      stocks: '',     // 库存
      lowStock: '',   // 库存预警值
      giftPoint: '',  // 赠送积分
      agentPoint: '', // 金积分
      attribute: ''   // 销售属性（即规格对应的id，格式a1:v1;a2:v2）
    }

    // 根据所选规格，得到表格动态生成表格中规格字段
    for (const key in specsObj) {
      skuItem[key] = ''
    }
    
    // 根据选择的规格，计算得到对应sku数据
    let tableDatas = []
    for (const key in specsObj) {
      if(tableDatas.length === 0) {
        specsObj[key].list.forEach(item => {
          let newData = {...skuItem}
          newData[key] = `${item.attributeValue}`
          newData['attribute'] = `${key}:${item.attributeValueId}`
          newData['skuName'] = `${specsObj[key].specsName}:${item.attributeValue}`
          tableDatas.push(newData)
        })
      } else {
        let arrList = []
        for (let i = 0; i < tableDatas.length; i++) {
          let currentAttribute = tableDatas[i]['attribute']
          let currentSkuName = tableDatas[i]['skuName']
          specsObj[key].list.forEach((item => {
            tableDatas[i][key] = `${item.attributeValue}`
            tableDatas[i]['attribute'] = `${currentAttribute},${key}:${item.attributeValueId}`
            tableDatas[i]['skuName'] = `${currentSkuName},${specsObj[key].specsName}:${item.attributeValue}`
            arrList.push({...tableDatas[i]})
          }))
        }
        tableDatas = arrList
      }
    }

    // 处理已选规格中填写数据的项，保留填写的数据
    tableDatas.forEach(item => {
      currentData.form.skuList.forEach(e => {
        if(item.attribute === e.attribute) {
          for (const key in e) {
            item[key] = e[key]
          }
        }
      })
    })
    currentData.form.skuList = tableDatas
  }

  // 同步数据
  function doSyncData(key) {
    let syncData = 0
    currentData.form.skuList.forEach((item, index) => {
      if(index === 0) {
        syncData = item[key]
      } else {
        item[key] = syncData
      }
    })
  }

  function loadGoodSpecs(attributeCategoryId) {
    // 查询商品规格数据
    loadGoodsAttr(attributeCategoryId)
    // 查询商品参数数据
    loadGoodsParams(attributeCategoryId)
  }

  // 查询商品规格数据
  function loadGoodsAttr(attributeCategoryId) {
    getGoodsAttrApi(attributeCategoryId).then(res => {
      if(res.code === '200') {
        currentData.specs = res.data
        //根据规格数据生成表头数据
        let tableHeader = [
          {label: 'SKU图标', prop: 'skuPic'},
          {label: '出厂价', prop: 'oriPrice'},
          {label: '销售价', prop: 'salePrice'},
          {label: '库存', prop: 'stocks'},
          {label: '库存预警值', prop: 'lowStock'},
          {label: '赠送积分', prop: 'giftPoint'},
          {label: '金积分', prop: 'agentPoint'}
        ]
        currentData.specs.forEach((item, index) => {
          tableHeader.splice(index, 0, {label: item.name, prop: item.attributeId})
        })
        currentData.tableHeader = tableHeader
      }
    })
  }

  function loadGoodsParams(attributeCategoryId) {
    getGoodsParamsApi(attributeCategoryId).then(res => {
      if(res.code === '200') {
        currentData.argumentList = res.data
      }
    })
  }

  // 查询属性分类数据
  function loadAttrTypes(name) {
    if(!name) {
      return
    }
    currentData.loading = true
    getGoodsAttrTypeListApi({
      merchantId: window.sessionStorage.getItem('merchantId'),
      name: name
    }).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.attrTypes = res.data
      }
    })
  }
</script>

<style lang="less" scoped>
.goodsAttr{
  :deep(.el-card){
    margin-bottom: 15px;
    .el-card__header{
      display: flex;
      align-items: center;
      .el-icon{
        margin-right: 5px;
      }
    }
    .el-card__body{
      padding: 40px 40px 20px 0;
      .good_specs{
        width: 100%;
        .specs-box{
          display: flex;
          flex-direction: column;
          border-bottom: #dcdfe6 solid 1px;
          margin-bottom: 10px;
          .specs_item{
            display: flex;
            margin-bottom: 10px;
            .name{
              margin-right: 10px;
            }
            .specs_value{
              width: 80px;
              text-align: center;
              cursor: pointer;
              border-left: #eeeeee solid 1px;
              border-top: #eeeeee solid 1px;
              border-bottom: #eeeeee solid 1px;
              &:hover{
                background: #a0cfff;
                color: #ffffff;
              }
              &:last-child{
                border-right: #eeeeee solid 1px;
              }
            }
            .specs_active{
              background: #409EFF;
              color: #ffffff;
            }
          }
        }
        .el-table{
          margin-top: 10px;
          .sku-pic-box{
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
      .good_params{
        width: 350px;
        display: flex;
        flex-direction: column;
        .good_param_item{
          display: flex;
          align-items: center;
          justify-content: flex-end;
          margin-bottom: 10px;
          .paramName{
            text-align: right;
            margin-right: 10px;
          }
          .el-input, .el-select{
            width: 250px;
          }
        }
      }
      .input-w{
        width: 250px;
      }
      .btns{
        display: flex;
        justify-content: center;
      }
    }
  }
  
}
</style>